package com.itelite.aop;

import com.itelite.common.util.SecurityUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/9/1-16:54
 **/
@Aspect
@Component
@Slf4j
public class WebLogAop {
    /**
     * 定义切入点，切入点为com.example.aop下的所有函数
     */
    @Pointcut("execution(public * com.itelite.handler.GlobalExceptionHandler.*(..))")
    public void webLog(){}
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        log.info("异常处理");
        // 记录下请求内容
        log.info("URL :{} ",request.getRequestURL().toString());
        log.info("HTTP_METHOD {}",request.getMethod());
        log.info("IP : {}",request.getRemoteAddr());
        log.info("CLASS_METHOD : {}",joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS : {}" ,Arrays.toString(joinPoint.getArgs()));
    }



    /**
     * 定义切点
     * 该切点指向某个包,因此要求对应包内只有接口的方法，业务方法请分离到业务层
     * 使用@annotation指定切点为 自定义注解接口com.winning.WinControllerPointCut
     */
    @Pointcut("@annotation(com.itelite.aop.WinControllerPointCut)")
    public void winPointCut() {
    }

    @Before("winPointCut()")
    public void beforeCall(JoinPoint joinPoint) {
        MethodSignature sign = (MethodSignature) joinPoint.getSignature();
        Method method = sign.getMethod();
        String operation = method.getAnnotation(ApiOperation.class).value();
        log.info("操作： {} | 操作者：{}",operation,SecurityUtils.getRealName());
    }
}
